package com.mt.api.core.config.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: plover
 * @Date: 2020/08/08/10:35 上午
 * @Description:
 */
@WebFilter(filterName = "bodyReaderFilter", urlPatterns = "/*")
public class BodyReaderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        //重新封装请求body后，如果是上传类型的，会报错，目前没解决，暂时不对multipart/form-data类型的请求做处理
        if (request instanceof HttpServletRequest &&
                !StringUtils.containsIgnoreCase(request.getContentType(), "multipart/form-data")) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }

    }

    @Override
    public void destroy() {
        // do nothing

    }

}
